package com.gack.business.service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.gack.business.dao.DepartmentDao;
import com.gack.business.dao.UserDao;
import com.gack.business.dao.UserEnterpriseDepartmentPositionDao;
import com.gack.business.dao.UserEnterprisePermissionGroupDao;
import com.gack.business.model.Department;
import com.gack.business.model.Message;
import com.gack.business.model.UserEnterprisePermissionGroup;
import com.gack.business.repository.ContactsRepository;
import com.gack.business.repository.DepartmentRepository;
import com.gack.business.repository.EnterpriseRepository;
import com.gack.business.repository.MessageRepository;
import com.gack.business.repository.UserEnterpriseDepartmentPositionRepository;
import com.gack.business.repository.UserEnterprisePermissionGroupRepository;
import com.gack.business.repository.UserRepository;
import com.gack.business.vo.DepartmentItemVO;
import com.gack.business.vo.TopDepartmentAndUserItemVO;
import com.gack.business.vo.UserItemVO;
import com.gack.helper.common.util.Pinyin;

/**
 * 
 * @author ws
 * 2018-5-31
 */
@Service
@Transactional
public class DepartmentService implements DepartmentServiceInterface{

	@Autowired
	private UserRepository userRepository;
	@Autowired
	private UserDao userDao;
	@Autowired
	private EnterpriseRepository enterpriseRepository;
	@Autowired
	private DepartmentRepository departmentRepository;
	@Autowired
	private DepartmentDao departmentDao;
	@Autowired
	private UserEnterpriseDepartmentPositionRepository userEnterpriseDepartmentPositionRepository;
	@Autowired
	private UserEnterpriseDepartmentPositionDao userEnterpriseDepartmentPositionDao;
	@Autowired
	private ContactsRepository contactsRepository;
	@Autowired
	private MessageRepository messageRepository;
	@Autowired
	private UserEnterprisePermissionGroupRepository userEnterprisePermissionGroupRepository;
	@Autowired
	private UserEnterprisePermissionGroupDao userEnterprisePermissionGroupDao;

	/**
	 * 查询某部门的下一级子部门
	 * @param enterpriseId 公司id
	 * @param departmentId 部门id
	 * @return status:error/success msg:错误或成功消息  departmentItemList:部门ItemVO集合
	 */
	@Override
	public Map<String, Object> findNextDepartmentItem(String enterpriseId, String departmentId) {
		Map<String, Object> map = new HashMap<>();
		
		if(departmentRepository.countByEnterpriseIdAndDepartmentId(enterpriseId, departmentId) == 0){
			map.put("status", "success");
			map.put("msg", "该公司下无此部门");
			return map;
		}
		
		List<DepartmentItemVO> departmentItemList = departmentRepository.findNextSubDepartmentItemVOByDepartmentId(departmentId);
		
		map.put("departmentItemList", departmentItemList);
		map.put("status", "success");
		map.put("msg", "操作成功");
		
		return map;
	}
	
	/**
	 * 获取某部门下所有子部门id(全部子部门包含：层层嵌套子部门)
	 * @param departmentId 部门id
	 * @return
	 */
	@Override
	public List<String> findAllSubDepartmentId(String enterpriseId, String departmentId){
		List<String> allSubDepartmentIdList = new ArrayList<>();
		
		if(departmentId == null || departmentId.trim().length() == 0){
			return allSubDepartmentIdList;
		}
		
		List<String> subDepartmentIdList = departmentRepository.findNextSubDepartmentIdByDepartmentId(enterpriseId, departmentId);
		allSubDepartmentIdList.addAll(subDepartmentIdList);
		while(subDepartmentIdList != null && subDepartmentIdList.size() != 0){
			List<String> subTemp = null;
			Iterator<String> it = subDepartmentIdList.iterator();
			if(it.hasNext()){
				String t = it.next();
				subTemp = departmentRepository.findNextSubDepartmentIdByDepartmentId(enterpriseId, t);
				it.remove();
			}
			if(subTemp != null && subTemp.size() != 0){
				subDepartmentIdList.addAll(subTemp);
				allSubDepartmentIdList.addAll(subTemp);
			}
		}
		
		return allSubDepartmentIdList;
	}
	
	/**
	 * 获取某部门的父部门,及其父父部门的id
	 * @param departmentId 部门id
	 * @return 父部门id集合
	 */
	@Override
	public List<String> findAllParentDepartmentId(String departmentId){
		List<String> allParentDepartmentIdList = new ArrayList<>();
		
		if(departmentId == null || departmentId.trim().length() == 0){
			return allParentDepartmentIdList;
		}
		
		String parentId = departmentRepository.findParentDepartmentId(departmentId);
		while(!"0".equals(parentId)){
			allParentDepartmentIdList.add(0, parentId);
			parentId = departmentRepository.findParentDepartmentId(parentId);
		}
		
		return allParentDepartmentIdList;
	}
	
	/**
	 * 获取某部门的一级部门id
	 * @param departmentId 部门id
	 * @return
	 */
	@Override
	public String findTopParentIdByDepartmentId(String departmentId){
		if(departmentId == null || departmentId.trim().length() == 0){
			return null;
		}
		
		if(!departmentRepository.exists(departmentId)){
			return null;
		}
		
		String previousId = departmentId;
		String parentId = departmentRepository.findParentDepartmentId(departmentId);
		
		while(!"0".equals(parentId)){
			previousId = parentId;
			parentId = departmentRepository.findParentDepartmentId(previousId);
		}
		
		return previousId;
	}
	
	/**
	 * 用户查询某部门下的子部门信息以及当前部门人员信息(不包含子部门中人员信息)
	 * @param departmentId 部门id
	 * @param userId 用户id
	 * @return status:error/success  msg:错误或成功消息   hasSubDepartment:true/false hasUserItemList:true/false subDepartmentItemList:子部门ItemVO集合    userItemList:部门下人员ItemVO集合
	 */
	@Override
	public Map<String, Object> findSubDepartmentItemAndUserItem(String departmentId, String userId) {
		Map<String, Object> map = new HashMap<>();
		
		boolean hasDepartment = departmentRepository.exists(departmentId);
		if(!hasDepartment){
			map.put("status", "error");
			map.put("msg", "查无此部门");
			return map;
		}
		
		boolean hasUser = userRepository.exists(userId);
		if(!hasUser){
			map.put("status", "error");
			map.put("msg", "查无此用户");
			return map;
		}
		
		//查询下一级部门ItemVO
		List<DepartmentItemVO> subDepartmentItemVOList = departmentRepository.findNextSubDepartmentItemVOByDepartmentId(departmentId);
		if(subDepartmentItemVOList == null || subDepartmentItemVOList.size() == 0){
			map.put("hasSubDepartment", false);
		}else{
			//对subDepartmentItemVOList排序,按照部门名称
			Comparator<DepartmentItemVO> comparator = new Comparator<DepartmentItemVO>(){
				@Override
				public int compare(DepartmentItemVO d1, DepartmentItemVO d2) {
					String s1 = Pinyin.getStringPinYin(d1.getName());
					String s2 = Pinyin.getStringPinYin(d2.getName());
					return s1.compareTo(s2);
				}
			};
			Collections.sort(subDepartmentItemVOList, comparator);
			map.put("hasSubDepartment", true);
			map.put("subDepartmentItemList", subDepartmentItemVOList);
		}
		
		String enterpriseId = departmentRepository.findEnterpriseIdByDepartmentId(departmentId);
		List<String> departmentList = new ArrayList<>();
		departmentList.add(departmentId);
		List<UserItemVO> userItemVOListTmep = userDao.findUserItemVOByDepartmentIdList(enterpriseId, departmentList, userId);
		
		//若该部门下无人员ItemVO,则不进行合并操作,直接返回
		if(userItemVOListTmep.size() == 0){
			map.put("hasUserItemList", false);
			map.put("status", "success");
			map.put("msg", "操作成功");
			return map;
		}
		
		//建立游离状态的userItemVO对象集合
		List<UserItemVO> userItemVOList = new ArrayList<>();
		for(UserItemVO t : userItemVOListTmep){
			UserItemVO tt = new UserItemVO();
			tt.setId(t.getId());
			tt.setUsername(t.getUsername());
			tt.setPortrait(t.getPortrait());
			tt.setNameForShow(t.getNameForShow());
			tt.setRoleId(t.getRoleId());
			userItemVOList.add(tt);
		}
		
		//添加roleId
		List<UserEnterprisePermissionGroup> uepgList = userEnterprisePermissionGroupRepository.findManager(enterpriseId);
		for(UserItemVO t : userItemVOList){
			t.setRoleId("3");
			for(UserEnterprisePermissionGroup uepg : uepgList){
				if(uepg.getUserId().equals(t.getId())){
					if(uepg.getOpenDescription().contains("SUPER_PERMISSION")){
						t.setRoleId("1");
					}else{
						t.setRoleId("2");
					}
				}
			}
		}
		
		//对userVOList排序,按nameForShow排序
		Comparator<UserItemVO> comparator = new Comparator<UserItemVO>(){
			@Override
			public int compare(UserItemVO u1, UserItemVO u2) {
				String s1 = Pinyin.getStringPinYin(u1.getNameForShow());
				String s2 = Pinyin.getStringPinYin(u2.getNameForShow());
			
				return s1.compareTo(s2);
			}
		};
		Collections.sort(userItemVOList, comparator);
		
		map.put("hasUserItemList", true);
		map.put("userVOList", userItemVOList);
		map.put("status", "success");
		map.put("msg", "操作成功");
		
		return map;
	}
	
	/**
	 * 查询该公司的一级部门,并带有子部门的嵌套关系
	 * @param enterpriseId 公司id
	 * @return status:error/success  msg:错误或成功消息   topDepartmentItemList:一级部门ItemVO集合
	 */
	@Override
	public Map<String, Object> findAllDepartmentItem(String enterpriseId){
		Map<String, Object> map = new HashMap<>();
		
		boolean hasEnterprise = enterpriseRepository.exists(enterpriseId);
		if(!hasEnterprise){
			map.put("status", "error");
			map.put("msg", "查无此公司");
			return map;
		}
		
		List<DepartmentItemVO> allDepartmentItemVOList = departmentRepository.findAllDepartmentItemVOByEnterpriseId(enterpriseId);
		
		for(DepartmentItemVO t : allDepartmentItemVOList){
			for(DepartmentItemVO t1 : allDepartmentItemVOList){
				if(t1.getParentId().equals(t.getId())){
					t.getSubDepartmentItemVOList().add(t1);
				}
			}
		}
		
		List<DepartmentItemVO> topDepartmentItemVOList = new ArrayList<>();

		Iterator<DepartmentItemVO> it = allDepartmentItemVOList.iterator();
		while(it.hasNext()){
			DepartmentItemVO t = it.next();
			if(t.getParentId().equals("0")){
				it.remove();
				topDepartmentItemVOList.add(0, t);
			}
		}
		
		//对topDepartmentItemVOList进行排序
		Comparator<DepartmentItemVO> comparator = new Comparator<DepartmentItemVO>(){
			@Override
			public int compare(DepartmentItemVO d1, DepartmentItemVO d2) {
				String s1 = Pinyin.getStringPinYin(d1.getName());
				String s2 = Pinyin.getStringPinYin(d2.getName());
				return s1.compareTo(s2);
			}
		};
		Collections.sort(topDepartmentItemVOList, comparator);
		
		map.put("status", "success");
		map.put("msg", "操作成功");
		map.put("topDepartmentItemList", topDepartmentItemVOList);
		
		return map;
		
	}
	
	/**
	 * 获取某公司的一级部门ItemVO,不带有子部门的嵌套关系
	 * @param enterpriseId 公司id
	 * @return status:error/success  msg:错误或成功消息   topDepartmentItemList:一级部门ItemVO集合
	 */
	@Override
	public Map<String, Object> findTopDepartmentItem(String enterpriseId) {
		Map<String, Object> map = new HashMap<>();
		
		boolean hasEnterprise = enterpriseRepository.exists(enterpriseId);
		if(!hasEnterprise){
			map.put("status", "error");
			map.put("msg", "查无此公司");
			return map;
		}
		
		List<DepartmentItemVO> topDepartmentItemList = departmentRepository.findTopDepartmentItemVOByEnterpriseId(enterpriseId);
	
		//对topDepartmentAndUserVOList按departmentName排序
		Comparator<DepartmentItemVO> comparator = new Comparator<DepartmentItemVO>(){
			@Override
			public int compare(DepartmentItemVO d1, DepartmentItemVO d2) {
				String s1 = Pinyin.getStringPinYin(d1.getName());
				String s2 = Pinyin.getStringPinYin(d2.getName());
				return s1.compareTo(s2);
			}
		};
		Collections.sort(topDepartmentItemList, comparator);
		
		map.put("topDepartmentItemList", topDepartmentItemList);
		map.put("status", "success");
		map.put("msg", "操作成功");
		return map;
	}

	/**
	 * 新增部门   不能出现同名情况
	 * @param enterpriseId 公司id
	 * @param parentDepartmentId 父部门id
	 * @param newDepartmentName 新部门名称
	 * @return status:error/success  msg:错误或成功消息(hasName)
	 */
	@Override
	public Map<String, Object> insertDepartment(String enterpriseId, String parentDepartmentId, String newDepartmentName) {
		Map<String, Object> map = new HashMap<>();
		
		boolean hasEnterprise = enterpriseRepository.exists(enterpriseId);
		if(!hasEnterprise){
			map.put("status", "error");
			map.put("msg", "查无此公司");
			return map;
		}
		
		//检查该公司下是否存在该部门, 若新增一级部门,则无需该检查
		if(departmentRepository.countByEnterpriseIdAndDepartmentId(enterpriseId, parentDepartmentId) == 0 && parentDepartmentId != "0"){
			map.put("status", "error");
			map.put("msg", "此公司下无此部门");
			return map;
		}
		
		//检查该部门下子部门数量是否已达上限(00-zz,上限数量为1296)
		int subDepartmentCount = departmentRepository.countSubDepartmentByDepartmentIdIncludeDeleted(enterpriseId, parentDepartmentId);
		if(subDepartmentCount >= 1296){
			map.put("status", "error");
			map.put("msg", "此部门下子部门数量已达上限,无法新增子部门");
			return map;
		}
		
		//检查父部门下的子部门中是否存在重名情况
		if(departmentRepository.countSameNameByParentmentId(enterpriseId, parentDepartmentId, newDepartmentName) > 0){
			map.put("status", "error");
			map.put("msg", "有重名情况,请修改后再试");
			return map;
		}
		
		Department newDepartment = new Department();
		String parentNo = parentDepartmentId.equals("0")?"":departmentRepository.findNoByDepartmentId(parentDepartmentId);//父部门编号
		String newNo = String.valueOf(Integer.toString(subDepartmentCount+1, 36));
		newNo = newNo.length()==1?"0"+newNo:newNo;
		newDepartment.setNo(parentNo + newNo);//设置部门编号
		newDepartment.setName(newDepartmentName);//设置部门名称
		newDepartment.setEnterpriseId(enterpriseId);//设置部门的所属公司
		newDepartment.setNumber(0);//设置部门的初始人数,为0
		newDepartment.setParentId(parentDepartmentId);//设置父部门id 无父部门,则为"0"
		newDepartment.setSurplus_amount(0);//设置部门剩余可用额度(分）
		newDepartment.setUsed_amount(0);//设置部门已用额度(分)
		newDepartment.setStatus(1);//设置部门状态(0:已删除   1:未删除)
		newDepartment.setUpdateNameTime(new Date());//设置部门更改名称时间
		if(parentDepartmentId.equals("0")){
			newDepartment.setLevel("0");
		}else{
			String parentDepartmentLevel = departmentRepository.findLevelById(parentDepartmentId);
			newDepartment.setLevel(String.valueOf((Integer.parseInt(parentDepartmentLevel) + 1) ) );
		}
		departmentRepository.save(newDepartment);
		
		map.put("status", "success");
		map.put("msg", "操作成功");
		return map;
	}
	
	/**
	 * 批量修改部门名称
	 * @param enterpriseId 公司id
	 * @param departmentIdAndNewName 部门id和新名称     格式为:部门id@;-;@新名称;=;=;部门id@;-;@新名称
	 * @param operatorUserId 操作者id
	 * @return  status:error/success  msg:错误或成功消息(hasName)
	 */
	@Override
	public Map<String, Object> updateDepartmentNameByBatch(String enterpriseId, String departmentIdAndNewName, String operatorUserId) throws Exception{
		Map<String, Object> map = new HashMap<>();
		
		//将departmentIdAndNewName字符串拆分成部门id和部门新名称
		String[] departmentId_newName = departmentIdAndNewName.split(";=;=;");
		for(String t : departmentId_newName){
			String[] t1 = t.split("@;-;@");
			 map = updateDepartmentName(enterpriseId, t1[0], t1[1], operatorUserId);
			if(map.get("status").equals("error")){
				throw new RuntimeException("---msg:" + (String)map.get("msg"));
			}
		}
		
		return map;
	}
	
	/**
	 * 修改部门名称  若存在重名情况,则不能修改
	 * @param enterpriseId 公司id
	 * @param departmentId 部门id
	 * @param newDepartmentName 部门新名称
	 * @param operatorUserId 操作者id
	 * @return status:error/success  msg:错误或成功消息(hasName)
	 */
	@Override
	public Map<String, Object> updateDepartmentName(String enterpriseId, String departmentId, String newDepartmentName, String operatorUserId) {
		Map<String, Object> map = new HashMap<>();
		
		boolean hasEnterprise = enterpriseRepository.exists(enterpriseId);
		if(!hasEnterprise){
			map.put("status", "error");
			map.put("msg", "查无此公司");
			return map;
		}
		
		//检查该公司下是否存在该部门
		if(departmentRepository.countByEnterpriseIdAndDepartmentId(enterpriseId, departmentId) == 0){
			map.put("status", "error");
			map.put("msg", "此公司下无此部门");
			return map;
		}
		
		//检查该部门的父部门的子部门中,是否有重名情况
		if(departmentRepository.countSameNameByDepartmentIdExcludeMe(enterpriseId, departmentId, newDepartmentName) > 0){
			map.put("status", "error");
			map.put("msg", "有重名情况,请修改后再试");
			return map;
		}
		
		Department department = departmentRepository.findOne(departmentId);
		if(department == null){
			map.put("status", "error");
			map.put("msg", "查无此部门");
			return map;
		}
		
		String oldDepartmentName = department.getName();
		
		department.setName(newDepartmentName);
		department.setUpdateNameTime(new Date());
		departmentRepository.save(department);
		
		//获取该部门的所有子部门id
		List<String> allSubDepartmentIdList = findAllSubDepartmentId(enterpriseId, departmentId);
		allSubDepartmentIdList.add(departmentId);
		
		//获取该部门及其子部门及子子部门的人员id
		List<String> userIds = userEnterpriseDepartmentPositionDao.findUserIdByEnterpriseIdAndDepartmentIds(enterpriseId, allSubDepartmentIdList);
		
		String enterpriseName = enterpriseRepository.findNameById(enterpriseId);
		String enterpriseRemarks = userEnterpriseDepartmentPositionRepository.findEnterpriseRemarks(operatorUserId, enterpriseId);
		
		//userIds中添加部门管理人员
		List<UserEnterprisePermissionGroup> uepgList = userEnterprisePermissionGroupRepository.findManager(enterpriseId);
		for(UserEnterprisePermissionGroup element : uepgList){
			if(element.getOpenDescription().contains("MANAGE_DEPARTMENT")){
				userIds.add(element.getUserId());
			}
		}
		//去重
		Set<String> set = new HashSet<>(userIds);
		userIds = new ArrayList<>(set);
		
		for(String t : userIds){
			String friendRemarks = contactsRepository.findFriendRemarks(operatorUserId, t);
			
			String text = "";
			if(friendRemarks != null && friendRemarks.trim().length() != 0){
				text = "管理员【" + friendRemarks + "】已将" + enterpriseName + "的" + oldDepartmentName + "改名为" + newDepartmentName;
			}else{
				text = "管理员【" + enterpriseRemarks + "】已将" + enterpriseName + "的" + oldDepartmentName + "改名为" + newDepartmentName;
			}
			
			Message message = new Message();
			//向公司的员工发送消息,告知管理权限的解除
			message.setUserid(t);//设置接受者id
			message.setMessage(text);//设置消息内容
			message.setCreatetime(new Date());//设置创建时间
			message.setTitle("系统消息");//设置标题
			message.setMesType(5);//设置消息类型为"系统消息"
			message.setState(2);//设置消息状态为"未处理"
			message.setCreateId(operatorUserId);//设置创建者id
			message.setSendWay(2);//设置发送方式为"站内信"
			message.setIsRead(0);//设置为"未读"
			messageRepository.save(message);
		}
		
		map.put("status", "success");
		map.put("msg", "操作成功");
		
		return map;
	}
	
	/**
	 * 批量删除某些部门
	 * @param enterpriseId 公司id
	 * @param departmentIds 部门id集合
	 * @param operatorId 操作者id
	 * @return
	 */
	@Override
	public Map<String, Object> deleteDepartmentByBatch(String enterpriseId, String[] departmentIds, String operatorId) throws Exception{
		Map<String, Object> map = new HashMap<>();
		
		for(String t : departmentIds){
			map = deleteDepartment(enterpriseId, t, operatorId);
			if(map.get("status").equals("error")){
				throw new RuntimeException("---msg:" + (String)map.get("msg"));
			}
		}
		
		return map;
	}
	
	/**
	 * 删除某部门及其下属子部门,并将相应人员所在部门置为null,将相应权限删除,再将其父部门及父父部门的人数相应减少
	 * @param enterpriseId 公司id
	 * @param departmentId 部门id
	 * @param operatorId 操作者id
	 * @return status:error/success msg:错误或成功消息
	 */
	@Override
	public Map<String, Object> deleteDepartment(String enterpriseId, String departmentId, String operatorId){
		Map<String, Object> map = new HashMap<>();
		
		boolean hasEnterprise = enterpriseRepository.exists(enterpriseId);
		if(!hasEnterprise){
			map.put("status", "error");
			map.put("msg", "查无此公司");
			return map;
		}
		
		//检查该公司下是否存在该部门
		if(departmentRepository.countByEnterpriseIdAndDepartmentId(enterpriseId, departmentId) == 0){
			map.put("status", "error");
			map.put("msg", "此公司下无此部门");
			return map;
		}
		
		String departmentName = departmentRepository.findNameById(departmentId);
		
		//获取该部门的所有子部门id
		List<String> allSubDepartmentIdList = findAllSubDepartmentId(enterpriseId, departmentId);
		allSubDepartmentIdList.add(departmentId);
		
		//获取该部门及其子部门及子子部门的人员id
		List<String> userIds = userEnterpriseDepartmentPositionDao.findUserIdByEnterpriseIdAndDepartmentIds(enterpriseId, allSubDepartmentIdList);
		String enterpriseName = enterpriseRepository.findNameById(enterpriseId);
		String enterpriseRemarks = userEnterpriseDepartmentPositionRepository.findEnterpriseRemarks(operatorId, enterpriseId);
		
		//userIds中添加部门管理人员
		List<UserEnterprisePermissionGroup> uepgList = userEnterprisePermissionGroupRepository.findManager(enterpriseId);
		for(UserEnterprisePermissionGroup element : uepgList){
			if(element.getOpenDescription().contains("MANAGE_DEPARTMENT")){
				userIds.add(element.getUserId());
			}
		}
		//去重
		Set<String> set = new HashSet<>(userIds);
		userIds = new ArrayList<>(set);
		
		for(String t : userIds){
			String friendRemarks = contactsRepository.findFriendRemarks(operatorId, t);
			
			String text = "";
			if(friendRemarks != null && friendRemarks.trim().length() != 0){
				text = "管理员【" + friendRemarks + "】已将" + enterpriseName + "的" + departmentName + "删除";
			}else{
				text = "管理员【" + enterpriseRemarks + "】已将" + enterpriseName + "的" + departmentName + "删除";
			}
			
			Message message = new Message();
			//向公司的员工发送消息,告知管理权限的解除
			message.setUserid(t);//设置接受者id
			message.setMessage(text);//设置消息内容
			message.setCreatetime(new Date());//设置创建时间
			message.setTitle("系统消息");//设置标题
			message.setMesType(5);//设置消息类型为"系统消息"
			message.setState(2);//设置消息状态为"未处理"
			message.setCreateId(operatorId);//设置创建者id
			message.setSendWay(2);//设置发送方式为"站内信"
			message.setIsRead(0);//设置为"未读"
			messageRepository.save(message);
		}
		
		//减少其父部门及父父部门的相应人数
		int num = departmentDao.findUserNum(allSubDepartmentIdList);
		//获取该部门的父部门,及其父父部门
		List<String> allParentDepartmentIdList = findAllParentDepartmentId(departmentId);
		if(allParentDepartmentIdList != null && allParentDepartmentIdList.size() != 0){
			departmentDao.minusNDepartmentNumber(allParentDepartmentIdList, num);
		}
		
		//删除该部门及其子部门
		departmentDao.deleteDepartment(allSubDepartmentIdList);
		
		//将相应人员所在部门置为null
		userEnterpriseDepartmentPositionDao.setNullDepartment(allSubDepartmentIdList, new Date());
		
		//如果该部门为一级部门,则归还剩余可用额度
		String parentId = departmentRepository.findParentDepartmentId(departmentId);
		if(parentId.equals("0")){
			enterpriseRepository.updateEnterpriseSurplusAmountByDeleteDepartment(departmentId);
		}
		
		map.put("status", "success");
		map.put("msg", "操作成功");
		return map;
	}
	
	/**
	 * 查询某公司的第一级部门以及每个一级部门下的人员(包含子子部门的人员)
	 * @param enterpriseId 公司id
	 * @param userId 操作者id
	 * @return status:error/success msg:错误或成功消息  topDepartmentAndUserVOList:返回集合,按部门名称排序
	 */
	public Map<String, Object> findTopDepartmentAndUserItemVO(String enterpriseId, String userId){
		Map<String, Object> map = new HashMap<>();
		
		boolean hasEnterprise = enterpriseRepository.exists(enterpriseId);
		if(!hasEnterprise){
			map.put("status", "error");
			map.put("msg", "查无此公司");
			return map;
		}
		
		//查询该公司的一级部门id及name
		List<TopDepartmentAndUserItemVO> topDepartmentAndUserVOList = departmentRepository.findTopDepartmentAndUserItemVO(enterpriseId);
		
		//查询某一级部门下所有人员ItemVO
		for(TopDepartmentAndUserItemVO temp : topDepartmentAndUserVOList){
			//获取该部门的所有子部门id
			List<String> allSubDepartmentIdList = findAllSubDepartmentId(enterpriseId, temp.getDepartmentId());
			allSubDepartmentIdList.add(temp.getDepartmentId());
			
			List<UserItemVO> userItemVOListTmep = userDao.findUserItemVOByDepartmentIdList(enterpriseId, allSubDepartmentIdList, userId);
			
			//删除操作者
			for(UserItemVO t : userItemVOListTmep){
				if(t.getId().equals(userId)){
					userItemVOListTmep.remove(t);
					break;
				}
			}
			
			//建立游离状态的userItemVO对象集合
			List<UserItemVO> userItemVOList = new ArrayList<>();
			for(UserItemVO t : userItemVOListTmep){
				UserItemVO tt = new UserItemVO();
				tt.setId(t.getId());
				tt.setUsername(t.getUsername());
				tt.setPortrait(t.getPortrait());
				tt.setNameForShow(t.getNameForShow());
				tt.setRoleId(t.getRoleId());
				userItemVOList.add(tt);
			}
			
			//添加roleId
			List<UserEnterprisePermissionGroup> uepgList = userEnterprisePermissionGroupRepository.findManager(enterpriseId);
			for(UserItemVO t : userItemVOList){
				t.setRoleId("3");
				for(UserEnterprisePermissionGroup uepg : uepgList){
					if(uepg.getUserId().equals(t.getId())){
						if(uepg.getOpenDescription().contains("SUPER_PERMISSION")){
							t.setRoleId("1");
						}else{
							t.setRoleId("2");
						}
					}
				}
			}
			
			//放置某一级部门对应全部人员ItemVO(包含子子部门的人员ItemVO)
			temp.setUserItemVOList(userItemVOList);
		}
		
		//对topDepartmentAndUserVOList按departmentName排序
		Comparator<TopDepartmentAndUserItemVO> comparator = new Comparator<TopDepartmentAndUserItemVO>(){
			@Override
			public int compare(TopDepartmentAndUserItemVO t1, TopDepartmentAndUserItemVO t2) {
				String s1 = Pinyin.getStringPinYin(t1.getDepartmentName());
				String s2 = Pinyin.getStringPinYin(t2.getDepartmentName());
				return s1.compareTo(s2);
			}
		};
		Collections.sort(topDepartmentAndUserVOList, comparator);
		
		//加入无部门及无部门人员
		TopDepartmentAndUserItemVO noDepartmentAndUserItemVO = new TopDepartmentAndUserItemVO();
		noDepartmentAndUserItemVO.setDepartmentId("-1");//设置无部门id为-1
		noDepartmentAndUserItemVO.setDepartmentName("无部门");
		List<UserItemVO> noDepartmentUserItemVOList = userDao.findNoDepartmentUserItemVO(enterpriseId, userId);
		//删除操作者
		for(UserItemVO t : noDepartmentUserItemVOList){
			if(t.getId().equals(userId)){
				noDepartmentUserItemVOList.remove(t);
				break;
			}
		}
		//建立游离状态的userItemVO对象集合
		List<UserItemVO> userItemVOList = new ArrayList<>();
		for(UserItemVO t : noDepartmentUserItemVOList){
			UserItemVO tt = new UserItemVO();
			tt.setId(t.getId());
			tt.setUsername(t.getUsername());
			tt.setPortrait(t.getPortrait());
			tt.setNameForShow(t.getNameForShow());
			tt.setRoleId(t.getRoleId());
			userItemVOList.add(tt);
		}
		//添加roleId
		List<UserEnterprisePermissionGroup> uepgList = userEnterprisePermissionGroupRepository.findManager(enterpriseId);
		for(UserItemVO t : userItemVOList){
			t.setRoleId("3");
			for(UserEnterprisePermissionGroup uepg : uepgList){
				if(uepg.getUserId().equals(t.getId())){
					if(uepg.getOpenDescription().contains("SUPER_PERMISSION")){
						t.setRoleId("1");
					}else{
						t.setRoleId("2");
					}
				}
			}
		}
		if(userItemVOList != null && userItemVOList.size() > 0){
			noDepartmentAndUserItemVO.setUserItemVOList(userItemVOList);
			topDepartmentAndUserVOList.add(noDepartmentAndUserItemVO);
		}
		
		map.put("topDepartmentAndUserVOList", topDepartmentAndUserVOList);
		map.put("status", "success");
		map.put("msg", "操作成功");
		
		return map;
	}
}
